package main

import (
	"encoding/json"
	"fmt"
	"log"
	"math/rand"
	"net/http"
	"os"
	"regexp"
	"strings"
	"time"

	_ "github.com/mattn/go-sqlite3"
	"google.golang.org/api/youtube/v3"
)

type Data struct {
	UniversalComments []string
	SpecificComments  []string
	Channels          []Channel
}

type Channel struct {
	Name string `json:"name"`
	Url  string `json:"url"`
}

func insertComment(service *youtube.Service, videoId string, comment string) error {
	call := service.CommentThreads.Insert([]string{"snippet"}, &youtube.CommentThread{
		Snippet: &youtube.CommentThreadSnippet{
			VideoId: videoId,
			TopLevelComment: &youtube.Comment{
				Snippet: &youtube.CommentSnippet{
					TextOriginal: comment,
				},
			},
		},
	})
	_, err := call.Do()
	if err != nil {
		return err
	}
	return nil
}

func main() {
	rand.Seed(time.Now().Unix())
	db := initDB()
	defer db.Close()
	service := initService()
	b, err := os.ReadFile("data.json")
	if err != nil {
		log.Fatalf("Unable to read comments file: %v", err)
	}
	var data Data
	json.Unmarshal(b, &data)
	insertChannels(db, &data.Channels)
	client := http.Client{}
	channelRegex := regexp.MustCompile(`"videoId":"(.*?)"`)
	for {
		for _, channel := range data.Channels {
			bytes, err := RequestChannel(&client, &channel)
			if err != nil {
				log.Println(err)
				continue
			}
			if !strings.Contains(string(bytes), `"videoId":"`) {
				continue
			}
			videoId := string(channelRegex.FindSubmatch(bytes)[1])
			lastVideoID := getLastID(db, &channel)
			if lastVideoID == videoId {
				time.Sleep(time.Second * 4)
				continue
			}
			var comment string
			if rand.Intn(2) == 0 {
				comment = data.UniversalComments[rand.Intn(len(data.UniversalComments))]
			} else {
				comment = fmt.Sprintf(data.SpecificComments[rand.Intn(len(data.SpecificComments))], channel.Name)
			}
			updateLastID(db, &channel, videoId)
			err = insertComment(service, videoId, comment)
			if err != nil {
				log.Println(err.Error())
				continue
			}
			log.Printf("Commented `%s` to %s", comment, fmt.Sprintf("https://www.youtube.com/watch?v=%s", videoId))
		}
		time.Sleep(time.Minute)
	}
}
